package com.meisiabc.utils;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;


public class PictureMerge {
    public static BufferedImage merge(URL file, URL waterFile, int x, int y, float alpha) throws IOException {
        BufferedImage buffImg = ImageIO.read(file);
        BufferedImage waterImg = ImageIO.read(waterFile);
        return process(buffImg, waterImg, x, y, alpha);
    }

    public static BufferedImage merge(URL file, InputStream waterFile, int x, int y, float alpha) throws IOException {
        BufferedImage buffImg = ImageIO.read(file);
        BufferedImage waterImg = ImageIO.read(waterFile);
        return process(buffImg, waterImg, x, y, alpha);
    }

    private static BufferedImage process(BufferedImage buffImg, BufferedImage waterImg, int x, int y, float alpha) {
        Graphics2D g2d = buffImg.createGraphics();
        int waterImgWidth = waterImg.getWidth() - 100;// 获取层图的宽度
        int waterImgHeight = waterImg.getHeight() - 100;// 获取层图的高度
        g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha));// 在图形和图像中实现混合和透明效果
        g2d.drawImage(waterImg, x, y, waterImgWidth, waterImgHeight, null);// 绘制
        g2d.dispose();// 释放图形上下文使用的系统资源
        return buffImg;
    }
}
